<?php

class Groups extends HTech_Db_Table implements Emms_Interface_LoanApplication
{
    protected $_name    = 'view_groups';
    protected $_primary = 'GroupId';
    
    protected $_dependentTables = array('Clients');
    
    protected $_referenceMap    = array(
        'Banks' => array(
            'columns'           => array('BankId'),
            'refTableClass'     => 'Banks',
            'refColumns'        => array('BankId')
        )
    );
    
    protected function _setGridMetadata()
    {
        $this->_gridMetadata['title'] = $this->translate("Groups");
        $this->_gridMetadata['titleMods'] = array('LocationShortName','OfficerUsername');
        $this->_gridMetadata['params'] = array('OfficerUserId','LocationId','BankId','CommunityId');
        $this->_gridMetadata['onClick'] = 'admin.group.view';
        $this->_gridMetadata['headers'] = array
            (
                array('GroupId',          120, $this->translate("Group code"), 'Number'),
                array('BankId',           120, $this->translate("Bank code"),  'Number'),
                array('OfficerUsername',  120, $this->translate("Officer"),    'String'),
                array('LocationShortName', 80, $this->translate("Branch"),     'String'),
                array('Community',        250, $this->translate("Community"),  'String'),
                array('Name',             300, $this->translate("Group"),      'String')
            );
        return $this;
    }
    
    protected function _setRecordDependentRows()
    { 
        $this->_record->r = (object) array('clients' => null);
        $this->_record->r->clients = $this->_record->d->findDependentRowset('Clients');  
    }
    
    static function add($bankId)
    {
        require_once 'Banks.php';
        $banks = new Banks();
        try { $bankRecord = $banks->getRecord($bankId); } catch (Exception $e) { return; }
                   
        $groups = new Groups(array('name' => 'groups'));
            
        $c = $groups->fetchAll($groups->select()->where('BankId = ?', $bankId))->count();
        if ($c >= Zend_Registry::get('HT_Config')->portfolio->group->max) return;
        $group = $groups->createRow();
        $group->BankId = $bankId;
        $group->Name = sprintf(Zend_Registry::get('HT_Config')->portfolio->group->name, $bankRecord->d->Name, $c + 1);
        $group->LastEditUserId = Zend_Auth::getInstance()->getIdentity()->UserId;
        $group->LastEditDate = date('Y-m-d H:i:s');
        $group->save();
        $banks->resetChildren($bankId);        
    }
    
    static function deactivate($groupId)
    {
        require_once 'Banks.php';
        $groups = new Groups(array('name' => 'groups'));           
        try { $group = $groups->getRecord($groupId); } catch (Exception $e) { return; }
        if ($group->r->clients->count() != 0) return;        
        $banks = new Banks();
        $bankRecord = $banks->getRecord($group->d->BankId);        
        $group->d->BankId = 0;
        $group->d->save();
        $banks->resetChildren($bankRecord->d->BankId);        
        return $bankRecord->d->BankId;
    }
    
    static function getGroupOptions($type = '', $id = 0)
    {
        switch($type) {
            case 'Officer':
                return ($id ? array('--- ' . self::translate('Individual')) : array()) + 
                    Zend_Registry::get('db')->fetchPairs("select GroupId, Name from view_groups where OfficerUserId != 0 and OfficerUserId = ? order by Name", $id);
            case 'Bank':
                return Zend_Registry::get('db')->fetchPairs('select GroupId, Name from groups where BankId = ?', $id);
            case 'Client':
                require_once 'Clients.php';
                if(Clients::getActiveLoansCount($id)) {
                    $groups = Zend_Registry::get('db')->fetchPairs('select g.GroupId, g.Name 
                        from view_groups g, view_clients c where g.GroupId = c.GroupId and c.ClientId = ?', $id);
                    return count($groups) > 0 ? $groups : array('--- ' . self::translate('Individual'));
                } else {
                    return array('--- ' . self::translate('Individual')) + 
                        Zend_Registry::get('db')->fetchPairs("select g.GroupId, g.Name from view_groups g, view_clients c 
                            where g.OfficerUserId = c.OfficerUserId and c.ClientId = ? order by Name", $id);
                }
        }
        return array();
    }
    
    public function getLoanApplicationData($id) 
    {
        $record = $this->getRecord($id);
        return (object) array
        (
            'BorrowerType' => 'B',
            'Name' => $record->d->Name,
            'Code' => $record->d->GroupId,
            'Location' => $record->d->Location,
            'LocationId' => $record->d->LocationId,
            'Community' => $record->d->Community,
            'Officer' => $record->d->OfficerFullName,
            'OfficerUserId' => $record->d->OfficerUserId,
            'Clients' => $record->r->clients
        );
    }
}